package top.oneit.jdownload.stages;

import cn.hutool.core.lang.Assert;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import top.oneit.jdownload.JdownloadApplication;
import top.oneit.jdownload.utils.XmlUtils;

import java.net.URL;

/**
 * @author lingkang
 * @date 2021/11/10
 */
@Slf4j
public class BaseStage extends Stage {
    public FXMLLoader fxmlLoader;
    private String thisClassName=getClass().getName();
    public BaseStage() {
        // 存储场景
        JdownloadApplication.stages.put(thisClassName, this);

        // 场景关闭
        setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                // 关闭自身
                close();
            }
        });
    }

    @Override
    public void close() {
        super.close();
        removeStage();
    }

    private void removeStage() {
        if (JdownloadApplication.stages.containsKey(thisClassName)) {
            JdownloadApplication.stages.remove(thisClassName);
            log.info("close {}", thisClassName);
        }
    }

    /**
     * 获取对象,,注意返回空值
     */
    protected <T> T getStage(Class<T> clazz) {
        Stage stage = JdownloadApplication.stages.get(clazz.getName());
        if (stage == null)
            return null;
        return (T) JdownloadApplication.stages.get(clazz.getName());
    }

    protected void setXML(String xmlPath){
        URL resource = XmlUtils.class.getResource(xmlPath);
        fxmlLoader = new FXMLLoader(resource);
        try {
            Scene scene = new Scene(fxmlLoader.load());// 加载场景
            setScene(scene);
        } catch (Exception e) {
            e.printStackTrace();
            Assert.isNull(e, "加载xml失败！");
        }
    }

    protected Session getSession(){
        return JdownloadApplication.sessionFactory.openSession();
    }

    protected <T> T save(T o) {
        Session session = JdownloadApplication.sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.save(o);
        session.getTransaction().commit();
        return o;
    }
}
